// import { useAsync } from "./use-async";
// import { cleanObject } from "./index";
import { useHttp } from "./http";
// import { useCallback, useEffect } from "react";
import { QueryKey, useMutation, useQuery } from "react-query";
// import { useProjectsSearchParams } from "../screens/project-list/util";
import {
  useAddConfig,
  useDeleteConfig,
  useEditConfig,
} from "./use-optimistic-options";
import { Project } from "../types/project";

const isVoidPrivate = (value: unknown) =>
  value === undefined || value === null || value === "" || value === 0;
//去除对象中的空属性
export const cleanObjectPrivate = (object: { [key: string]: unknown }) => {
  let result = { ...object };
  Object.keys(result).forEach((key) => {
    const value = object[key];
    if (isVoidPrivate(value)) {
      delete result[key];
    }
  });
  return result;
};

export const useProjects = (param?: Partial<Project>) => {
  // const { run, ...result } = useAsync<Project[]>()

  const client = useHttp();
  //react-query指定返回值
  //   return useQuery<Project[], Error>(['projects', param], () =>client('/projects', {data: cleanObjectPrivate(param || {}) }))
  return useQuery<Project[]>(["projects", param], () =>
    client("/projects", { data: cleanObjectPrivate(param || {}) })
  );
  // const fetchProjects = useCallback(
  //   () => client('/projects', {data: cleanObjectPrivate(param || {}) }), [client, param]
  // )
  // useEffect(() => {
  //   run(fetchProjects(), {
  //     retry: fetchProjects
  //   })
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  // }, [param])
  // return {
  //   ...result
  // }
};

export const useEditProject = (queryKey: QueryKey) => {
  const client = useHttp();
  // const queryClient = useQueryClient()
  // const [searchParams] = useProjectsSearchParams()
  // const queryKey = ['projects', searchParams]
  return useMutation(
    (params: Partial<Project>) => {
      return client(`/projects/${params.id}`, {
        data: params,
        method: "PATCH",
      });
    },
    useEditConfig(queryKey)
    // {
    // onSuccess: () => queryClient.invalidateQueries('projects'),
    // async onMutate(target) {
    //   const previousItems = queryClient.getQueryData(queryKey)
    //   queryClient.setQueryData(queryKey, (old?: Project[]) => {
    //     return old?.map(project => project.id === target.id? { ...project, ...target }: project) || []
    //   })
    //   return {previousItems}
    // },
    // onError(error,newItem, context: any) {
    //   queryClient.setQueryData(queryKey, context.previousItems)
    // }
    // }
  );
  // const {run, ...asyncResult} = useAsync()
  // const mutate = (params: Partial<Project>) => {
  //   console.log(params);
  //
  //   return run(client(`/projects/${params.id}`, {
  //     data: params,
  //     method: 'PATCH'
  //   }))
  // }
  // return {
  //   mutate,
  //   ...asyncResult
  // }
};
export const useAddProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Project>) =>
      client(`/projects`, {
        data: params,
        method: "POST",
      }),
    useAddConfig(queryKey)
  );
  // const {run, ...asyncResult} = useAsync()
  // const mutate = (params: Partial<Project>) => {
  //   return run(client(`projects/${params.id}`, {
  //     data: params,
  //     method: 'post'
  //   }))
  // }
  // return {
  //   mutate,
  //   ...asyncResult
  // }
};
export const useDeleteProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    ({ id }: { id: number }) =>
      client(`/projects/${id}`, {
        method: "DELETE",
      }),
    useDeleteConfig(queryKey)
  );
};

export const useProject = (id?: number) => {
  const client = useHttp();
  return useQuery<Project>(
    ["project", { id }],
    () => client(`/projects/${id}`),
    {
      enabled: !!id,
    }
  );
};
